import requests
from matplotlib import pyplot as plt


def get_city(city):
    url = "https://api.seniverse.com/v3/weather/now.json"
    params = {
        "key": "xxxxxxxxxxx",  # 私钥
        "location": city,
        "language": "zh-Hans",
        "unit": "c",
    }
    # 获取数据
    r = requests.get(url, params=params)
    # 解析数据
    data = r.json()["results"]
    # 获取温度
    temp = data[0]['now']["temperature"]  # 温度
    return int(temp)


if __name__ == '__main__':
    cities = ["北京", "上海", "广州", "深圳", "东莞", "杭州", "惠州", "茂名", "佛山", "中山"]
    temp = []
    # 获取各个城市的温度
    for city in cities:
        temp.append(get_city(city))

    print(cities, "\n", temp)

    # 绘制柱状图
    plt.figure(figsize=(15, 8))
    plt.bar(cities, temp, color='skyblue')
    plt.ylim(20,30)
    # 显示中文
    plt.rcParams['font.sans-serif'] = ['SimHei']
    # 图像标注
    plt.title("十个城市的今日气温")
    plt.xlabel("城市")
    plt.ylabel("温度(℃)")
    # 显示图像
    plt.show()
